<template>
  <el-upload action="/api/upload/uploadImg" list-type="picture-card" :show-file-list="false" name="img" :on-success="handleAvatarSuccess" class="avatar-uploader"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>


  </el-upload>

  
</template>
<script setup>
import { ref,watchEffect } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus'

// 侦听


//   定义props默认接收的数据
let props = defineProps(['modelValue'])
// 定义emit的事件
let emit = defineEmits(['update:modelValue'])
//   上传成功的钩子
let imageUrl = ref('')
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  // console.log(response);
  emit('update:modelValue', response.imgUrl)
}
// 上传之前的钩子 控制文件上传的大小和格式
const beforeAvatarUpload = (rawFile) => {
  let rawType = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
  if (!rawType.includes(rawFile.type)) {
    ElMessage.error('上传的图片必须是' + rawType.join(',') + '中的一种')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片的大小不能超过1MB!')
    return false
  }
  return true
}
// 侦听imageUrl的变化
watchEffect(()=>{
  if(props.imageUrl!==''){
    imageUrl.value = props.modelValue
  }
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>